package com.bum.api.core.util.render;

import java.text.MessageFormat;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.bum.base.util.Base64Utils;

public class MediaCodeUtil {
	public static final int	MEDIA_TYPE_UNKNOWN	= 0;
	public static final int	MEDIA_TYPE_PHOTO	= 1;
	public static final int	MEDIA_TYPE_SOUND	= 2;
	public static final int	MEDIA_TYPE_VIDEO	= 3;
	public static final int	MEDIA_TYPE_APP		= 4;
	public static final int	MEDIA_TYPE_OTHER	= 5;

	public static int		VIEW_MEDIA_PHOTO	= 1;

	public static int getMediaType(String mediaCode) {
		if (mediaCode != null && mediaCode.length() > 1) {
			char type = mediaCode.toUpperCase().charAt(1);
			switch (type) {
				case 'P':
					return MEDIA_TYPE_PHOTO;
				case 'S':
					return MEDIA_TYPE_SOUND;
				case 'V':
					return MEDIA_TYPE_VIDEO;
				case 'A':
					return MEDIA_TYPE_APP;
				case 'O':
					return MEDIA_TYPE_OTHER;
			}
		}
		return MEDIA_TYPE_UNKNOWN;
	}

	public static String displayMediaAsHtml(String mediaCode) {
		return displayMediaAsHtml(mediaCode, null);
	}

	public static String displayMediaAsHtml(String mediaCode, String rel) {
		rel = StringUtils.trimToEmpty(rel);

		String url = new String(Base64Utils.decode(mediaCode));
		if (url.contains(".appspot.com/fetch")) {
			url = "http://tool.cdn.bum.vn/fetch?code=" + mediaCode;
		}
		return MessageFormat.format(
				"<a class=\"media\" href=\"{0}\" target=\"bum_media\"><span><img src=\"{0}\" rel=\"{1}\" class=\"img-thumb lazy\"/></span></a>", url, rel);
	}

	public static String displayMediaAsHtml(String mediaCode, int width, int height) {
		String displayUrl = "http://web.kaspee.com/";

		int type = getMediaType(mediaCode);
		switch (type) {
			case MEDIA_TYPE_PHOTO:
				displayUrl = MessageFormat.format("/media/{0}/view.html", mediaCode);
				String thumbUrl = MessageFormat.format("http://web.kaspee.com/view.jpg?wm=true&q=0.85&w={1}&h={2}&c={0}", mediaCode, width, height);
				return MessageFormat.format("<div class=\"me-media\"><a href=\"{0}\"><img data-src=\"{1}\" class=\"thumb lazy\"/></a></div>", displayUrl,
						thumbUrl);

			case MEDIA_TYPE_SOUND:
				displayUrl += "view?af=mp3&c=" + mediaCode;
				return "<div><a href=\"" + displayUrl + "\"><img src=\"/m/i.png\" class=\"i i32\"/>Tải MP3</a></div>";

			case MEDIA_TYPE_VIDEO:
				displayUrl += "view?c=" + mediaCode;
				return "<div><a href=\"" + displayUrl + "\"><img src=\"/m/i.png\" class=\"i i31\"/>Tải Video</a></div>";
		}

		return "";
	}

	public static void getTypeViewMediaPhoto(String viewType) {
		VIEW_MEDIA_PHOTO = NumberUtils.createInteger(viewType);
	}
}
